<template>
  <div class="box">
    <van-nav-bar :title="userType==1?'患者注册':'医护注册'"
                 left-arrow
                 @click-left="$router.go(-1);" />
    <div class="info">
      <van-cell-group>
        <van-field label="姓名"
                   label-width="5.7em"
                   v-model.trim="user.nickname"
                   placeholder="请输入姓名" />
        <!-- 患者 -->
        <van-field v-if="userType==1"
                   @focus="fieldSelect"
                   label-width="5.7em"
                   label="出生日期"
                   is-link
                   @click="dateShow=true"
                   v-model.trim="user.birthday"
                   placeholder="请选择出生日期" />
        <van-field v-if="userType==1"
                   label-width="5.7em"
                   @focus="fieldSelect"
                   label="性别"
                   is-link
                   @click="xingbieShow=true"
                   v-model.trim="gender"
                   placeholder="请选择性别" />
        <van-field v-if="userType==1"
                   label-width="5.7em"
                   label="体重（Kg）"
                   v-model.trim="user.weight"
                   placeholder="请输入体重（kg）" />
        <van-field v-if="userType==1"
                   label-width="5.7em"
                   label="身高（cm）"
                   v-model.trim="user.height"
                   placeholder="请输入身高（cm）" />
        <!-- 医护 -->
        <van-field v-if="userType==2"
                   label-width="5.7em"
                   label="省份"
                   @focus="fieldSelect"
                   is-link
                   @click="shengShow=true"
                   v-model.trim="user.province"
                   placeholder="请选择省份" />
        <van-field v-if="userType==2"
                   label-width="5.7em"
                   label="城市"
                   @focus="fieldSelect"
                   is-link
                   @click="cityShow=true"
                   v-model.trim="user.city"
                   placeholder="请选择城市" />
        <van-field v-if="userType==2"
                   label-width="5.7em"
                   label="医院名称"
                   @focus="fieldSelect"
                   is-link
                   @click="nameShow=true"
                   v-model.trim="user.hospital"
                   placeholder="请选择医院名称" />
        <van-field v-if="userType==2"
                   label-width="5.7em"
                   label="科室"
                   @focus="fieldSelect"
                   is-link
                   @click="keshiShow=true"
                   v-model.trim="user.department"
                   placeholder="请选择科室" />
        <van-field v-if="userType==2"
                   label-width="5.7em"
                   label="类型"
                   @focus="fieldSelect"
                   is-link
                   @click="leixingShow=true"
                   v-model.trim="user.type"
                   placeholder="请选择类型" />
        <van-field v-if="userType==2"
                   label="职称"
                   label-width="5.7em"
                   @focus="fieldSelect"
                   is-link
                   @click="zhichengShow=true"
                   v-model.trim="user.professional"
                   placeholder="请选择职称" />
        <van-field label="手机号"
                   label-width="5.7em"
                   v-model.trim="user.mobile"
                   placeholder="请输手机号" />
        <van-field label="密码"
                   label-width="5.7em"
                   v-model.trim="user.password"
                   placeholder="请输密码" />
        <van-field v-model="user.code"
                   center
                   label-width="5.7em"
                   clearable
                   label="验证码"
                   placeholder="请输入验证码">
          <template #button>
            <van-button :disabled="!disabledCodeBtn"
                        @click="getCode"
                        size="small"
                        class="code">{{codeText}}</van-button>
          </template>
        </van-field>
      </van-cell-group>
      <!-- 性别选择器 -->
      <van-popup v-model="xingbieShow"
                 round
                 position="bottom">
        <van-picker title="性别"
                    show-toolbar
                    :columns="xingbieList"
                    value-key="name"
                    @confirm="xingBie"
                    @cancel="xingbieShow=false" />
      </van-popup>
      <van-popup v-model="shengShow"
                 round
                 position="bottom">
        <van-picker title="省份"
                    show-toolbar
                    :columns="shenList"
                    @confirm="shengFen"
                    @cancel="shengShow=false" />
      </van-popup>
      <van-popup v-model="cityShow"
                 round
                 position="bottom">
        <van-picker title="城市"
                    show-toolbar
                    :columns="cityList"
                    @confirm="chengShi"
                    @cancel="cityShow=false" />
      </van-popup>
      <van-popup v-model="nameShow"
                 round
                 position="bottom">
        <van-picker title="医院名称"
                    show-toolbar
                    :columns="yiyuanList"
                    @confirm="Name"
                    @cancel="nameShow=false" />
      </van-popup>
      <van-popup v-model="keshiShow"
                 round
                 position="bottom">
        <van-picker title="科室"
                    show-toolbar
                    :columns="keshiList"
                    @confirm="keShi"
                    @cancel="keshiShow=false" />
      </van-popup>
      <van-popup v-model="leixingShow"
                 round
                 position="bottom">
        <van-picker title="类型"
                    show-toolbar
                    :columns="leixingList"
                    @confirm="leiXing"
                    @cancel="leixingShow=false" />
      </van-popup>
      <van-popup v-model="zhichengShow"
                 round
                 position="bottom">
        <van-picker title="职称"
                    show-toolbar
                    :columns="zhichengList"
                    @confirm="zhiCheng"
                    @cancel="zhichengShow=false" />
      </van-popup>
      <!-- 选择出生年月 -->
      <van-popup v-model="dateShow"
                 round
                 position="bottom">
        <van-datetime-picker v-model="currentDate"
                             type="date"
                             title="选择年月日"
                             :min-date="minDate"
                             :max-date="maxDate"
                             @cancel="dateShow=false"
                             @confirm="dateDay" />
      </van-popup>
    </div>
    <button class="btn"
            @click="register">注册</button>
  </div>
</template>
<script>
import dayjs from 'dayjs'
import { register, provinceList, getCityByProvice, getHospitalByCity, getDepartByHospital, professionalList, sendMobileCode } from '@/api/login.js'
export default {
  name: 'Register',
  data () {
    return {
      zhichengShow: false,
      keshiShow: false,
      leixingShow: false,
      nameShow: false,
      cityShow: false,
      shengShow: false,
      // 出生年月选择器
      dateShow: false,
      currentDate: new Date(),
      minDate: new Date(1850, 0, 1),
      maxDate: new Date(2022, 10, 1),
      // 性别选择器
      xingbieShow: false,
      codeText: '获取验证码',
      disabledCodeBtn: true,
      userType: '',
      gender: '',
      user: {
        identity: ''
        // birthday: '1970-01-01'
      },
      shenList: [],
      cityList: [],
      yiyuanList: [],
      keshiList: [],
      leixingList: ['医生', '护士', '药师'],
      zhichengList: [],
      xingbieList: [
        { name: '男', value: 1 },
        { name: '女', value: 0 }
      ],

      baseMap: { // 备份
        province_list: [], // 省列表
        city_list: [], // 城市
        hospital_list: [], // 医院
        department_list: [] // 科室
      }
    }
  },
  created () {
    this.userType = this.$route.query.userType
    this.user.identity = this.$route.query.userType
  },
  mounted () {
    // 获取省份
    this.provinceList()
    // 获取职称 - 没有上级可以直接拿
    this.professionalList()
  },
  methods: {
    fieldSelect () {
      document.activeElement.blur()
    },
    // 获取省份
    async provinceList () {
      const { code, msg, data } = await provinceList()
      if (code !== 1) return this.$toast.fail(msg)
      this.baseMap.province_list = data // 备份
      this.shenList = data.map(it => it.province)
    },
    // 根据省id 获取市
    async getCityByProvice (province_id) {
      const { code, msg, data } = await getCityByProvice({ province_id })
      if (code !== 1) return this.$toast.fail(msg)
      this.baseMap.city_list = data // 备份
      this.cityList = data.map(it => it.city)
    },
    // 根据市id获取医院列表
    async getHospitalByCity (city_id) {
      const { code, msg, data } = await getHospitalByCity({ city_id })
      if (code !== 1) return this.$toast.fail(msg)
      this.baseMap.hospital_list = data
      this.yiyuanList = data.map(it => it.hospital)
    },
    // 根据医院id获取科室列表
    async getDepartByHospital (hospital_id) {
      const { data, msg, code } = await getDepartByHospital({ hospital_id })
      if (code !== 1) return this.$toast.fail(msg)
      this.baseMap.department_list = data
      this.keshiList = data.map(it => it.department)
    },
    // 下级-职称列表
    async professionalList () {
      const { data, code, msg } = await professionalList()
      if (code !== 1) return this.$toast.fail(msg)
      this.zhichengList = data.map(it => it.name)
    },
    // 手机号正则
    checkPhone (phone) {
      return (/^1[3456789]\d{9}$/.test(phone))
    },
    // 注册
    register () {
      if (!this.user.nickname) return this.$toast.fail('姓名不能为空')
      if (this.userType === '1') { // 患者
        if (!this.user.birthday) return this.$toast.fail('出生日期不能为空')
        if (!this.user.gender) return this.$toast.fail('性别不能为空')
        if (!this.user.weight) return this.$toast.fail('体重不能为空')
        if (!this.user.height) return this.$toast.fail('身高不能为空')
      }
      if (this.userType === '2') { // 医护
        if (!this.user.province) return this.$toast.fail('省份不能为空')
        if (!this.user.city) return this.$toast.fail('城市不能为空')
        if (!this.user.hospital) return this.$toast.fail('医院名称不能为空')
        if (!this.user.department) return this.$toast.fail('科室不能为空')
        if (!this.user.type) return this.$toast.fail('类型不能为空')
        if (!this.user.professional) return this.$toast.fail('职称不能为空')
      }
      if (!this.checkPhone(this.user.mobile)) return this.$toast.fail('手机号格式不正确')
      if (!this.user.password) return this.$toast.fail('密码不能为空')
      if (!this.user.code) return this.$toast.fail('验证码不能为空')
      register(this.user).then(res => {
        const { code, msg, data } = res
        if (code !== 1) return this.$toast.fail(res.msg)
        this.$store.commit('SET_TOKEN', data.userinfo.token)
        this.$store.commit('SET_USER_INFO', data.userinfo)
        this.$store.commit('SET_USER_TYPE', this.userType)
        this.$toast.success(msg)
        const path = this.userType === '1' ? '/home' : '/home_'
        this.$router.push(path)
      })
    },
    // 出生年月确定
    dateDay (value) {
      this.user.birthday = dayjs(value).format('YYYY-MM-DD')
      this.dateShow = false
    },
    // 确认选择省份
    shengFen (event, index) {
      this.user.province = event // 选择省份赋值回显
      const province_id = this.baseMap.province_list[index].id // 拿到id
      this.getCityByProvice(province_id) // 获取市id
      this.shengShow = false // 关闭弹出层
    },
    // 确认选择城市
    chengShi (event, index) {
      this.user.city = event
      const city_id = this.baseMap.city_list[index].id
      this.getHospitalByCity(city_id)
      this.cityShow = false
    },
    // 确认选择医院
    Name (event, index) {
      this.user.hospital = event
      const hospital_id = this.baseMap.hospital_list[index].id
      this.user.hospital_id = hospital_id
      this.getDepartByHospital(hospital_id)
      this.nameShow = false
    },
    // 确认选择科室
    keShi (event, index) {
      this.user.department = event
      this.user.department_id = this.baseMap.department_list[index].id
      this.keshiShow = false
    },
    // 确认选择职称
    zhiCheng (event) {
      this.user.professional = event
      this.zhichengShow = false
    },
    // 确认选择类型
    leiXing (event, index) {
      this.user.type = event
      this.user.type_id = index + 1
      this.leixingShow = false
    },
    // 性别确定
    xingBie (event) {
      console.log(event)
      this.gender = event.name
      this.user.gender = event.value.toString()
      this.xingbieShow = false
    },
    // 获取验证码
    async getCode () {
      const _p = { mobile: this.user.mobile, event: 'register' }
      const { code, msg } = await sendMobileCode(_p)
      if (code !== 1) return this.$toast.fail(msg)
      this.countDown(60)
    },
    // 倒计时
    countDown (time) {
      if (time === 0) {
        this.disabledCodeBtn = true
        this.codeText = '获取验证码'
        return
      } else {
        this.disabledCodeBtn = false
        this.codeText = time + 's'
        time--
      }
      setTimeout(() => {
        this.countDown(time)
      }, 1000)
    }
  }
}
</script>
<style scoped lang='less'>
/deep/.van-cell {
  line-height: 32px;
}
/deep/.van-cell__title {
  width: 70px;
  font-weight: 600;
}
.box {
  width: 100%;
  height: 100%;
  background: #f7f8fa;
  .info {
    width: 100%;
    margin-top: 50px;
    background-color: #ffffff;
    margin-bottom: 30px;
  }
}
// 验证码
.code {
  width: 83px;
  height: 30px;
  background: linear-gradient(180deg, #68e0cf 0%, #209cff 100%);
  opacity: 1;
  border-radius: 4px;
  color: #ffffff;
  font-size: 10px;
}
.btn {
  display: block;
  margin: 0 auto;
  width: 80%;
  height: 48px;
  background: linear-gradient(90deg, #3eb3ff 0%, #436eff 100%);
  box-shadow: 0px 8px 20px rgba(29, 90, 255, 0.32);
  border-radius: 45px;
  color: #ffffff;
  font-size: 20px;
  border: none;
  margin: 0 auto;
}
</style>
